package org.dant.ant.extension.net.processors;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

import org.dant.ant.extension.net.Processor;
import org.dant.ant.extension.tasks.commands.CommandsConstants;
import org.dant.ant.extension.tasks.internal.Endpoint;
import org.dant.ant.extension.tasks.internal.RemoteCommand;
import org.dant.ant.extension.tasks.internal.RemoteResponse;
import org.dant.ant.extension.utils.FileUtil;

public class CopyProcessor implements Processor {

    public void process(RemoteCommand req, RemoteResponse response) {
        response.setCommandType(req.getName());
        if (CommandsConstants.DANT_CMD_COPY.equals(req.getName())) {
            int posi = -1;
            boolean complete = true;
            try {
                if (req.getParameter("position") != null) 
                    posi = ((Integer)req.getParameter("position")).intValue();
                if (req.getParameter("complete") != null)
                    complete = ((Boolean)req.getParameter("complete")).booleanValue();
        
                byte[] b = (byte[])req.getParameter("bytearray");
                String fulldestpath = (String)req.getParameter("fulldestpath");

                FileUtil.writeFile(b,
                                   fulldestpath,
                                   posi,
                                   complete);

            } catch (Exception ioe) {
                response.setSuccess(false);
                response.setResult("Exception during writing file: " + ioe.toString());
                ioe.printStackTrace();
                return;
            }
            if (complete) {
                StringBuffer sb = new StringBuffer();
                sb.append("Copied a file from [ ");
                sb.append(req.getSourceHost());
                sb.append(" @ ");
                sb.append(req.getParameter("fullsourcepath"));
                sb.append(" ]  to  [ ");
                sb.append(Endpoint.getLocalhost());
                sb.append(" @ ");
                sb.append(req.getParameter("fulldestpath"));
                sb.append(" ] ");
                System.out.println(sb.toString());    
                response.setResult(sb.toString());
            }
        } else {
            response.setSuccess(false);
            response.setResult("Required a COPY command, but is not a COPY command");
        }
    }
}
